package com.shameit.goodqrinfomanager.source.http;

import android.text.TextUtils;
import android.util.Log;

import com.shameit.goodqrinfomanager.MyApplication;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import me.goldze.mvvmhabit.utils.SPUtils;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class WebClient {
//    private String Baseurl = "http://qrcode.hzrq.cn";
    private String Baseurl = "http://47.96.71.26:8888";
    private WebClient() {
        createClient();
    }

    private static class holder {
        public static WebClient instance = new WebClient();
    }

    public static WebClient getInstance() {
        return holder.instance;
    }

    private void createClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                try {
                    Log.d("OKHTTP", message);
                    System.out.println(message);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("OKHTTP", message);
                    System.out.println(e.getMessage());
                }
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(new HeaderInterceptor())//设置Header
//                .addInterceptor(new QueryInterceptor())
                //.addNetworkInterceptor(cacheInterceptor)//设置缓存
                //.addInterceptor(cacheInterceptor)
                .addInterceptor(loggingInterceptor)
                //.cache(cache)
                // .sslSocketFactory(SslContextFactory.getSSLSocketFactoryForTwoWay())  // https认证 如果要使用https且为自定义证书 可以去掉这两行注释，并自行配制证书。
                // .hostnameVerifier(new SafeHostnameVerifier())
                .connectTimeout(30, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(30, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(30, TimeUnit.SECONDS)//设置写的超时时间
                .retryOnConnectionFailure(false);//错误重连


        OkHttpClient client = builder.build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(SPUtils.getInstance().getString(MyApplication.BaseUrl,"http://47.96.71.26:8888"))
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiService = retrofit.create(ApiService.class);
    }


    private ApiService apiService;

    public ApiService getApiService() {
        return apiService;
    }


    class CacheInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
//            if (!NetUtils.isNetworkConnected()) {//没网强制从缓存读取(必须得写，不然断网状态下，退出应用，或者等待一分钟后，就获取不到缓存）
//                Log.d("TAG", "当前无网络");
//                request = request.newBuilder()
//                        .cacheControl(CacheControl.FORCE_CACHE)
//                        .build();
//            } else {
//                Log.d("TAG", "当前有网络");
//                request = request.newBuilder()
//                        .cacheControl(CacheControl.FORCE_NETWORK)
//                        .build();
//            }
            Response response = chain.proceed(request);
            if (NetUtils.isNetworkConnected()) {//有网情况下，从服务器获取
                int maxAge = 60 * 1000;
                // 有网络时, 缓存最大保存时长为60s
                response.newBuilder()
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .removeHeader("Pragma")
                        .build();
            } else {//没网情况下，一律从缓存获取
                // 无网络时，设置超时为30天
                int maxStale = 30 * 24 * 3600;
                response.newBuilder()
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .removeHeader("Pragma")
                        .build();
            }
            return response;
        }
    }

    class HeaderInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //处理业务逻辑，可以对header统一处理，涉及到header加密的也在此处理
            //......
//            request = builder.build();
            return chain.proceed(request);
        }

    }

    Interceptor cacheInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //有网的时候,读接口上的@Headers里的注解配置
            String cacheControl = request.cacheControl().toString();
            //没有网络并且添加了注解,才使用缓存.
            if (!NetUtils.isNetworkConnected()) {
                //重置请求体;
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            //如果没有添加注解,则不缓存
            if (TextUtils.isEmpty(cacheControl) || "no-store".contains(cacheControl)) {
                //响应头设置成无缓存
                cacheControl = "no-store";
            } else if (NetUtils.isNetworkConnected()) {
                //如果有网络,则将缓存的过期事件,设置为0,获取最新数据
                cacheControl = "public, max-age=" + 0;
            } else {
                //...如果无网络,则根据@headers注解的设置进行缓存.
            }
            Response response = chain.proceed(request);
            Log.i("httpInterceptor", cacheControl);
            return response.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")
                    .build();
        }
    };
}
